#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int i;
int main()
{
		
		char *p, *_p, *__p;
		char aStrTmp[1024];
		char aStrTmp_[1024];
		char aStrTmp__[1024];
		char ehangDirectory[256];
		char LocalAddress[64];
		strcpy(LocalAddress, "129.0.0.1");
		strcpy(ehangDirectory, ".");
		
		i++;
			memset(aStrTmp_, 0, 1024);
		
			snprintf(aStrTmp_, sizeof(aStrTmp_), 
				"%s/redis.conf", ehangDirectory);
		
			FILE *fp = fopen(aStrTmp_, "a+");
		
			if (fp == NULL) {
		
				printf("%s\n", aStrTmp_);
		
				exit(0);
		
			}
	        	
			memset(aStrTmp__, 0, 1024);
		
			snprintf(aStrTmp__, sizeof(aStrTmp__), 
				"%s/redis.conf.tmp", ehangDirectory);
		
			FILE *fp_ = fopen(aStrTmp__, "a+");
		
			if (fp_== NULL) {
		
				printf("%s\n", aStrTmp_);
		
				exit(0);
		
			}
		
			memset(aStrTmp, 0, sizeof(aStrTmp));
		
			while (fread(aStrTmp, 1, sizeof(aStrTmp), fp) > 0 ) {
				p = aStrTmp;
				while ((p = strstr(p, "bind"))) {
					printf("p-1:%c\np-2:%c\n", *(p-1), *(p-2));
					if ((*(p-1) != '#') && (*(p-2) != '#') 
						&& ((*(p-1) == '\n') || (*(p-2) == '\n'))) {
							
							_p = p;
						p = strchr(p, '\n') ;
						if (p == NULL) {
							printf("p is NULL\n");
							p = _p;
							p += 4;
							continue;
						}
						
						if ((strstr(_p, "127.0.0.1")	// 
							&& (strstr(_p, "127.0.0.1") - p) > 0)) {
								__p = strstr(_p, "127.0.0.1");
								if (strchr(__p, ' ')) {
									//127.0.0.1后续存在ip，直接替换它
									__p = strchr(__p, ' ');
									memmove(__p, p, strlen(p));
									memmove(p + strlen(LocalAddress) + 1, p, strlen(p));						
									*p = ' ';
									memcpy(p + 1, LocalAddress, strlen(LocalAddress));
								} else {	//不存在，直接加						
									memmove(p + strlen(LocalAddress) + 1, p, strlen(p));						
									*p = ' ';
									memcpy(p + 1, LocalAddress, strlen(LocalAddress));
								}
						} else {	//不存在127.0.0.1，直接加
							memmove(p + strlen(LocalAddress) + 1, p, strlen(p));						
							*p = ' ';
							memcpy(p + 1, LocalAddress, strlen(LocalAddress));
						}
						
					} else {
						p +=4;
					}
				}
				int j = 0;
				p = NULL;
				p = aStrTmp;
		
				printf("%s", aStrTmp);
				while((j = fwrite(p, 1, strlen(p), fp_))) {
					p += j;
		
				}
			}
			fclose(fp);
			fclose(fp_);
			//unlink(aStrTmp_);
			//rename(aStrTmp__, aStrTmp_);
}
